<template>

    <!-- <a-input-search placeholder="按部门名称搜索…" style="margin-bottom: 10px" @search="onSearch" allowClear /> -->
   <a-tree v-if="!treeReloading" :treeData="treeData" :checkedKeys="curCheckedKeys" @select="onSelect" checkable
            @check="onCheck"></a-tree>
    <a-empty v-else description="暂无数据" />

</template>

<script setup lang="ts">
import { inject, nextTick, ref } from 'vue';
import type { TreeProps } from "ant-design-vue";

import { defHttp } from '/@/utils/http/axios';
const loadTreeDataApi = (params?) => defHttp.get({
    url: '/xl/xlCustomerType/tree', params
});


//spin是否加载
let loading = ref<boolean>(false);
// 树列表数据 - 默认数据
let treeData = ref<any[]>();
// 当前展开的项
let expandedKeys = ref<string[]>([]);
// 当前选中的项
let curSelectedKeys = ref<string[]>([]);//只有multiple  才能响应数组

//当选check的
let curCheckedKeys = ref<string[]>([]);
// 树组件重新加载
let treeReloading = ref<boolean>(false);

loadTreeData();
// 加载分类信息
async function loadTreeData() {
    loading.value = true;
    treeData.value = [];
    await loadTreeDataApi({
            pcode: -1,
            async: false
        }).then((result) => {
            if (Array.isArray(result)) {
                
                treeData.value = result;
                expandedKeys.value = ['0'];//自动展开
            }
        }).finally(() => (loading.value = false));;
}
function loadChildrenTreeData() {
    
}
//子组件定义emit 并触发，父组件监听
const emit = defineEmits(['selectTree']);

function onSelect(selectedKeys,e) {
    //debugger
    // if (selectedKeys.length > 0 && curSelectedKeys.value[0] !== selectedKeys[0]) {
    //     console.log(selectedKeys[0]);

    //     emit('selectTree', selectedKeys[0]);

    // } else {
    //     // 这样可以防止用户取消选择

    // }
    //debugger
    //curCheckedKeys.value.push( selectedKeys[0]);
    const clickedKey = e.node.key; // 获取点击的节点 key
    curCheckedKeys.value = [selectedKeys[0]]
    emit('selectTree', curCheckedKeys.value[0]);
}
// 处理复选框选中事件
const onCheck = (checkedKeys, info) => {
    
    // 只保留最新选中的节点
    const newCheckedKeys = checkedKeys.filter((key) => !info.halfCheckedKeys.includes(key));
    if (newCheckedKeys.length > 1) {
        // 如果选中了多个节点，只保留最后一个
        // setCheckedKeys([newCheckedKeys[newCheckedKeys.length - 1]]);
        curCheckedKeys.value = [newCheckedKeys[newCheckedKeys.length - 1]]
    } else {
        //setCheckedKeys(newCheckedKeys);
        curCheckedKeys.value = newCheckedKeys

    }
    emit('selectTree', curCheckedKeys.value[0]);
};
function handleSelect() {

}
function onExpand() {

}
function onSearch() {

}
</script>

<style scoped></style>